package com.yx.changdao.common.utils;

import com.yx.changdao.common.exception.AlertException;
import org.apache.commons.codec.CharEncoding;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 一些常用快捷方法组合; 避免冗余
 *
 * @author xiapeixin
 * @date 2020-3-28
 */
public final class Faster {


    public static String getStr(Object ...obj){

        StringBuilder str = new StringBuilder();
        for (Object o : obj) {
            if(Faster.isNull(o)){
                continue;
            }
            str.append(o.toString()+",");
        }
        str.deleteCharAt(str.length()-1);
        return str.toString();
    }
    /**
     * 1,2,3 转换为批量参数 (list)
     */
    public static List<Integer> batch2(String ids) {
        return Arrays.stream(ids.split(",")).filter(t -> {
            return !StringUtils.isEmpty(t)  && Character.isDigit(t.charAt(0)) ;
        }).map(Integer::parseInt).collect(Collectors.toList());
    }

    /**
     * 转换为,分隔的字符串
     * @return
     */
    public static String batch3(Collection<String> objs) {
        return objs.stream().reduce((x,y) -> x +"," +y).orElse("");
    }

    /**
     * 文件下载
     */
    public static void download(HttpServletResponse response, File file) throws IOException {

        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), CharEncoding.UTF_8).replace("+", "%20"));

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        //打开本地文件流
        InputStream inputStream = new FileInputStream(file);
        //激活下载操作
        OutputStream os = response.getOutputStream();

        //循环写入输出流
        byte[] b = new byte[2048];
        int length;
        while ((length = inputStream.read(b)) > 0) {
            os.write(b, 0, length);
        }
        // 这里主要关闭。
        os.close();
        inputStream.close();
    }


    //求百分比
    public static Double getPercentage(Integer tag, Integer all) {
        try {
            return new BigDecimal(tag).divide(new BigDecimal(all), 2, BigDecimal.ROUND_HALF_DOWN)
                    .multiply(new BigDecimal("100")).doubleValue();
        } catch (Exception e) {
            return 0.00;
        }
    }

    /**
     * 枚举值是否再合法的枚举序列中
     */
    public static <T> void throwNotIn(T t, List<T> list,String msg) throws AlertException {
        for (T ts : list) {
            if (ts.equals(t)) {
                return;
            }
        }
        throw new AlertException(msg == null ?t + "不包含在:" + list + "中":msg);
    }

    /**
     * 单个或多个对象转list, 适应于如:单个删除调用批量删除,转换参数
     */
    public static <T> List<T> toList(T... ts) {
        return new ArrayList<T>(Arrays.asList(ts));
    }

    /**
     * 如果对象为空或集合为空,则抛出异常
     */
    public static void throwNull(Object obj, String msg) throws AlertException {
        if (null == obj) {
            throw new AlertException(msg);
        }
        if (obj instanceof Collection) {
            if (((Collection) obj).isEmpty()) {
                throw new AlertException(msg);
            }
        }
        if (obj instanceof Map) {
            if (((Map) obj).isEmpty()) {
                throw new AlertException(msg);
            }
        }
    }

    public static void throwNull(Object obj) throws AlertException {
        throwNull(obj, "对象为空异常");
    }

    public static boolean isNull(Object obj) {
        return obj == null;
    }

    public static boolean isNotNull(Object obj) {
        return obj != null;
    }

    /**
     * 集合不为null ,且不为空
     */
    public static boolean IsNotEmpty(Collection<?> collection) {
        return collection != null && !collection.isEmpty();
    }


    public static boolean IsEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    /**
     * 集合不为null ,且不为空
     */
    public static boolean IsNotEmpty(Map<?, ?> map) {
        return map != null && !map.isEmpty();
    }

    public static Date now() {
        return new Date();
    }

    private Faster() {
    }
}
